package com.javaGather.demo2;


import java.util.ArrayList;

public class HashMapDemo<K, V> {

    //假设数组容量为10000-----扩容机制
    private Entry[] entrys = new Entry[10000];

    /**
     * hash冲突：拉链法
     * HashMap1.7---数组加链表   hash冲突 ----链表
     * HashMap1.8---数组加链表加红黑树
     *
     * @param <K>
     * @param <V>
     */

    static class Entry<K, V> {
        int hash;
        K k;
        V v;
        Entry<K, V> next;

        public Entry(K k, V v, int hash) {
            this.k = k;
            this.v = v;
            this.hash = hash;
        }
    }


    /**
     * 判断index是否有存放链表
     * 如果能够取出Entry对象
     *
     * @param k
     * @param v
     */
    public void put(K k, V v) {
        int hash = k.hashCode();
        int index = k.hashCode() % entrys.length;
        Entry oldEntry = entrys[index];
        if (oldEntry == null) {
            entrys[index] = new Entry<>(k, v, hash);
        } else {
            oldEntry.next = new Entry<>(k, v, hash);
        }
    }


    /**
     *
     * @param k
     * @return
     */
    public V get(K k) {
        //获取hash值
        int hash = k.hashCode();
        //计算hash存放位置   单链表
        int index = hash % entrys.length;
        //循环判断判断找到对应K
        for (Entry<K, V> entry = entrys[index]; entry != null; entry = entry.next) {
            if (entry.hash == hash && (entry.k.equals(k) || entry.k == k)) {
                //返回K对应的value
                return entry.v;
            }
        }
        return null;
    }

    public static void main(String[] args) {
        HashMapDemo<String, String> hashMapDemo = new HashMapDemo<>();
        hashMapDemo.put("123", "dsafsafsa");
        String s = hashMapDemo.get("123");
        System.out.println(s);
    }


}
